//
//  ChatViewController.m
//  group14
//
//  Created by lanou3g on 15/11/12.
//  Copyright © 2015年 吕志伟. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatTableViewCell.h"
#import "ChatTableViewCell2.h"
#import "UIView+MLInputDodger.h"
#import "SpeakOthers.h"



#define kSpeakOthers [SpeakOthers shareSpeakOthers]
#define kChatSql [ChatRecordSql shareChatRecordSql]

@interface ChatViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UIButton *SendButton;
@property (strong, nonatomic) IBOutlet UIButton *PhotoButton;
@property (strong, nonatomic) IBOutlet UITextField *MessageTextField;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *allMessages;//存放所有聊天消息
@property (nonatomic, strong) AVIMClient *client;

@property (nonatomic, strong) AVIMConversation *conversation;
@property (nonatomic, strong) NSString *idStr;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _allMessages = [NSMutableArray array];
    
    self.client = [[AVIMClient alloc] init];
    
    AVUser *user = [AVUser currentUser];
    
    AVQuery *query = [AVQuery queryWithClassName:@"_Conversation"];
    
    NSString *creatStr = [NSString stringWithFormat:@"%@and%@",user.username,_chatName];
    
    [query whereKey:@"name" equalTo:creatStr];
    
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
       
        _idStr = [object objectForKey:@"objectId"];
        
        if(!object)
        {
            // Tom 用自己的名字作为 ClientId 打开 client
            [self.client openWithClientId:user.username callback:^(BOOL succeeded, NSError *error) {
                // Tom 建立了与 Jerry 的会话
                [self.client createConversationWithName:creatStr clientIds:@[_chatName] callback:^(AVIMConversation *conversation, NSError *error)
                 {
                     _conversation = conversation;
                     [self loadChatMessage];
                     //通知接受者
                     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMessage:) name:@"message" object:nil];
                 }];
            }];

        }
        else
        {
            
            // Tom 用自己的名字作为 ClientId 打开 client
            [self.client openWithClientId:user.username callback:^(BOOL succeeded, NSError *error) {
                // Tom 查询 id 为 551260efe4b01608686c3e0f 的会话
                AVIMConversationQuery *query = [self.client conversationQuery];
                [query getConversationById:_idStr callback:^(AVIMConversation *conversation, NSError *error) {
                    if (succeeded) {
                        _conversation = conversation;
                        [self loadChatMessage];
                        //通知接受者
                        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMessage:) name:@"message" object:nil];
                    }
                }];
            }];
        }
        
        
    }];
    
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view addGestureRecognizer:tapG];
    
    self.navigationItem.title = _chatName;
    
    _tableView.separatorStyle = UITableViewCellEditingStyleNone;
    
    if(_allMessages.count != 0)
    {
        NSIndexPath *index = [NSIndexPath indexPathForRow:self.allMessages.count - 1 inSection:0];
        
        [self.tableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }
}
- (void)tap
{
    [self.view endEditing:YES];
}

- (void)loadChatMessage
{
    if(_idStr == nil)
    {
        NSLog(@"无聊天记录");
    }else
    {
        // Tom 创建查询会话的 query
        AVIMConversationQuery *query = [self.client conversationQuery];
        
        [query getConversationById:_idStr callback:^(AVIMConversation *conversation, NSError *error) {
            // 查询对话中最后 10 条消息
            [conversation queryMessagesWithLimit:20 callback:^(NSArray *objects, NSError *error) {
                NSLog(@"查询成功！");
                
                _allMessages = [NSMutableArray arrayWithArray:objects];
                
                NSLog(@"%@",objects);
                
                [self.tableView reloadData];
                
                if(_allMessages.count != 0)
                {
                    NSIndexPath *index = [NSIndexPath indexPathForRow:self.allMessages.count - 1 inSection:0];
                    
                    [self.tableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionBottom];
                }
                
            }];
        }];
    }
}

- (IBAction)sendMessageButtonClick:(id)sender {
    
    if([_MessageTextField.text isEqualToString:@""])
    {
        NSLog(@"你什么都没有输入...");
    }
    else
    {
        AVUser *user = [AVUser currentUser];
        
        AVIMTextMessage *message = [[AVIMTextMessage alloc] init];
        
        message.clientId = user.username;
        
        message.text = _MessageTextField.text;
        
        [_conversation sendMessage:message callback:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"发送成功！");
                
                [_allMessages addObject:[AVIMTextMessage messageWithText:_MessageTextField.text attributes:nil]];
                
                [self.tableView reloadData];
                
                _MessageTextField.text = @"";
                
                if(_allMessages.count != 0)
                {
                    NSIndexPath *index = [NSIndexPath indexPathForRow:self.allMessages.count - 1 inSection:0];
                    
                    [self.tableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionBottom];
                }
            }
        }];
    }
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    self.view.shiftHeightAsDodgeViewForMLInputDodger = 50.0f;
    
    [self.view registerAsDodgeViewForMLInputDodger];
}

- (void)loadMessage:(NSNotification *)message
{
    [_allMessages addObject:message.userInfo[@"MessageKey"]];
        
    [self.tableView reloadData];
        
    if(_allMessages.count != 0)
    {
        NSIndexPath *index = [NSIndexPath indexPathForRow:self.allMessages.count - 1 inSection:0];
        
        [self.tableView selectRowAtIndexPath:index animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allMessages.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AVIMTypedMessage *message = _allMessages[indexPath.row];
    
    if(message.ioType == AVIMMessageIOTypeIn)//发给当前用户
    {
        ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
        
        cell.MessageLabel.text = message.text;
        
        cell.selectionStyle = NO;
        
        return cell;
    }
    else
    {
        ChatTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
        cell.MessageLabel.text = message.text;
        
        cell.selectionStyle = NO;
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
